import {ListGroup} from "@bpmn-io/properties-panel";
import {is} from "bpmn-js/lib/util/ModelUtil";
import {
    addListenerFactory,
    getExtensionElementsList,
    getImplementationType,
    getListenersContainer,
    implementationDetails,
    removeListenerFactory
} from "../util"

const taskListenerGroup = {
    id: 'taskListener',
    label: 'Task Listeners',
    component:ListGroup,
    function:function (groups,element, translate,injector,register){
        let a = TaskListenerProps({
            element,
            translate,
            injector,
            register
        })
        return a;
    }
};
export default taskListenerGroup

function TaskListenerProps(props) {
    const {
        element,injector,register
    } = props;
    if (!is(element, 'bpmn:UserTask')) {
        return;
    }
    const bpmnFactory = injector.get('bpmnFactory'),
        commandStack = injector.get('commandStack');
    const translate = injector.get('translate');
    const businessObject = getListenersContainer(element);
    const type = "activiti:TaskListener"
    const listeners = getExtensionElementsList(businessObject, type) || [];
    const items = []
    for (let i = 0; i < listeners.length; i++) {
        let id = element.id + '-task-listener-' + i;
        let listener = listeners[i];
        items.push({
            id,
            label: getListenerLabel(listener,translate),
            entries: getEntries(element,id,register,translate,listener),
            remove: removeListenerFactory({ commandStack, element, listener, type})
        })
    }
    return {
        items,
        add: addListenerFactory({ element, bpmnFactory, commandStack, type })
    };
}
const IMPLEMENTATION_TYPE_TO_LABEL = {
    class: 'Java class',
    expression: 'Expression',
    delegateExpression: 'Delegate expression',
    script: 'Script'
};
const EVENT_TO_LABEL = {
    start: 'Start',
    end: 'End',
    take: 'Take',
    create: 'Create',
    assignment: 'Assignment',
    complete: 'Complete',
    delete: 'Delete',
    update: 'Update',
    timeout: 'Timeout'
};
function getListenerLabel(listener, translate) {
    const event = listener.get('event');
    const implementationType = getImplementationType(listener);
    const a = translate(EVENT_TO_LABEL[event]);
    const b = translate(IMPLEMENTATION_TYPE_TO_LABEL[implementationType]);
    return `${a}: ${b}`;
}

function getEntries(element,id,register,translate,listener){
    let arrs = ['eventType','listenerType'];
    const list = []
    for (let i = 0; i < arrs.length; i++) {
        let entries = register.findEntries(arrs[i],translate)
        entries = {...entries}
        entries.id = id;
        entries.listener =listener;
        list.push(entries)
    }
    implementationDetails(element,id,register,translate,listener,list);
    return list
}


